package com.hh.service.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.hh.common.request.RealNameAuthRequest;
import com.hh.common.utils.HttpUtils;
import com.hh.service.dao.UserDao;
import com.hh.service.service.user.RealNameAuthService;
import lombok.Data;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class RealNameAuthServiceImpl implements RealNameAuthService {

    @Resource
    private UserDao userDao;

    @Override
    public Boolean processAuthentication(RealNameAuthRequest request, Integer userId) {
        System.out.println(request);
        String host = "https://dfidveri.market.alicloudapi.com";
        String path = "/verify_id_name";
        String method = "POST";
        String appcode = "5b2b8f95ea6d41fcaa019e27230a1158";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("id_number", request.getIdCard());
        bodys.put("name", request.getRealName());


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */

            HttpResponse httpResponse = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String s = EntityUtils.toString(httpResponse.getEntity());
            ResultResponse resultResponse = JSONObject.parseObject(s, ResultResponse.class);
            if(resultResponse.getState() != null && resultResponse.getState() == 1){
                userDao.updateRealNameStatus(userId,request.getRealName(),request.getIdCard());
                return Boolean.TRUE;
            }else {
                return Boolean.FALSE;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }
}

@Data
class ResultResponse{
    private Integer state;
    private String status;
    private String resultMessage;
}
